<template>
  <div class="dashboard-container">
    <div class="app-container">
      <PageTools befor-show>
        <template #before>
          <span>共计
            <i>{{ page.total }}</i>
            条数据</span>
        </template>
        <template #after>
          <el-button size="small" type="warning" @click="$router.push('/import')">导入</el-button>
          <el-button size="small" type="danger" @click="exportData">导出</el-button>
          <el-button size="small" type="primary" @click="addRoleShow=true">新增员工</el-button>
        </template>
      </PageTools>
      <!-- 放置表格和分页 -->
      <el-card>
        <el-table border :data="list">
          <el-table-column label="序号" sortable="" type="index" />
          <el-table-column label="姓名" sortable="" prop="username" />
          <el-table-column label="头像" align="center">
            <template slot-scope="{row}">
              <!-- <img
                :src="row.staffPhoto || require('@/assets/common/bigUserHeader.png')"
                style="border-radius: 50%; width: 100px;height:100px; padding:10px"
                alt=""
              > -->
              <img
                v-imgerror="require('@/assets/common/bigUserHeader.png')"
                :src="row.staffPhoto "
                style="border-radius: 50%; width: 100px;height:100px; padding:10px"
                alt=""
                @click="clickStaffPhoto(row.staffPhoto)"
              >
            </template>
          </el-table-column>
          <el-table-column label="工号" sortable="" prop="workNumber" />
          <el-table-column label="聘用形式" sortable="" prop="formOfEmployment" :formatter="formatterHireType">
            <!-- 过滤器方法 -->
            <!-- <template v-slot="{row}">
              {{ row.formOfEmployment | hireType }}
            </template> -->
          </el-table-column>
          <el-table-column label="部门" sortable="" prop="departmentName" />
          <el-table-column label="入职时间" sortable="" prop="timeOfEntry">
            <template v-slot="{row}">
              {{ row.timeOfEntry | formatDate }}
            </template>
          </el-table-column>
          <el-table-column label="账户状态" sortable="" prop="enableState">
            <template v-slot="{row}">
              <el-switch
                :value="row.enableState === 1"
                active-color="#13ce66"
                inactive-color="#ff4949"
              />
            </template>
          </el-table-column>
          <el-table-column label="操作" sortable="" fixed="right" width="280">
            <template slot-scope="{row}">
              <el-button type="text" size="small" @click="$router.push(`employees/detail/${row.id}`)">查看</el-button>
              <el-button type="text" size="small">转正</el-button>
              <el-button type="text" size="small">调岗</el-button>
              <el-button type="text" size="small">离职</el-button>
              <el-button type="text" size="small" @click="editRole(row.id)">角色</el-button>
              <el-button type="text" size="small">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页组件 -->
        <el-row
          type="flex"
          justify="center"
          align="middle"
          style="height: 60px"
        >
          <el-pagination
            layout="prev, pager, next"
            :total="page.total"
            :page-size="page.size"
            :current-page.sync="page.page"
          />
        </el-row>
      </el-card>
      <!-- 新增员工 弹层 -->
      <el-dialog
        title="新增员工"
        :visible.sync="addRoleShow"
        width="70%"
        :before-close="addPopHandleClose"
      >
        <AddEmployee
          @addPopHandleClose="addPopHandleClose"
          @getEmployeeList="getEmployeeList"
        />
      </el-dialog>
      <!-- 二维码弹层 -->
      <el-dialog
        title="头像二维码"
        :visible.sync="heardDialogVisibleShow"
        center
        width="30%"
      >
        <el-row type="flex" justify="center">
          <canvas ref="mycanvas" />
        </el-row>
      </el-dialog>
      <!-- 角色组件 -->
      <AsignRole
        ref="AsignRoleRef"
        :user-id="userId"
      />
    </div>
  </div>
</template>

<script>
var QRCode = require('qrcode')
import AsignRole from './components/asign-role.vue'
import { getEmployeeListAPI } from '@/api/employee.js'
import EmployEnum from '@/api/constant/employees.js'
import AddEmployee from './components/add-employee.vue'
import { pick } from 'lodash'
import { formatDate } from '@/filters'
export default {
  name: 'Employees',
  components: {
    AddEmployee,
    AsignRole
  },
  // 定义过滤器
  filters: {
    hireType(val) {
      const { hireType } = EmployEnum
      const f = hireType.find(t => t.id === val)
      return f ? f.value : '未知'
    }
  },
  props: {},
  data() {
    return {
      list: [], // 接数据的
      page: {
        page: 1,
        size: 5,
        total: 0
      },
      addRoleShow: false,
      heardDialogVisibleShow: false,
      roleDilalogShow: false,
      userId: ''
    }
  },
  watch: {
    // 'page.page' :{
    //   handler(new,old){
    //     this.getEmployeeList(tihs.page)
    //   }
    // }
    'page.page': function() {
      this.getEmployeeList()
    }
  },
  created() {
    this.getEmployeeList()
  },
  mounted() {},
  methods: {
    async getEmployeeList() {
      const { rows, total } = await getEmployeeListAPI(this.page)
      this.list = rows
      this.page.total = total
    },
    formatterHireType(row, column, cellValue, index) {
      const { hireType } = EmployEnum
      const f = hireType.find(t => t.id === cellValue)
      return f ? f.value : '未知'
    },
    addPopHandleClose() {
      this.addRoleShow = false
    },
    async  exportData() {
      // 对照表
      const headers = {
        '手机号': 'mobile',
        '姓名': 'username',
        '入职日期': 'timeOfEntry',
        '聘用形式': 'formOfEmployment',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'
      }
      const { rows } = await getEmployeeListAPI({ page: 1, size: this.page.total })
      const data = rows.map(item => {
        // 得到对象中的项 取值
        const o = pick(item, Object.values(headers))
        // 处理时间格式
        o.timeOfEntry = formatDate(o.timeOfEntry)
        o.correctionTime = formatDate(o.correctionTime)
        // 处理聘用形式
        const f = EmployEnum.hireType.find(t => t.id === o.formOfEmployment)
        o.formOfEmployment = f ? f.value : '未知'
        // 把值转化为数组
        return Object.values(o)
      })
      import('@/vendor/Export2Excel').then(excel => {
        excel.export_json_to_excel({
          multiHeader: [['姓名', '主要信息', '', '', '', '', '部门']],
          merges: ['A1:A2', 'B1:F1', 'G1:G2'],
          header: Object.keys(headers), // 表头 必填
          data, // 具体数据 必填
          filename: 'excel-list', // 非必填
          autoWidth: true, // 非必填
          bookType: 'xlsx' // 非必填
        })
      })
    },
    // 点击头像
    clickStaffPhoto(url) {
      this.heardDialogVisibleShow = true
      this.$nextTick(() => {
        QRCode.toCanvas(this.$refs.mycanvas, url, function(error) {
          if (error) console.error(error)
          console.log('success!')
        })
      })
    },
    // 角色编辑
    async editRole(id) {
      await this.$refs.AsignRoleRef.getUserDetailById(id)
      this.$refs.AsignRoleRef.roleDilalogShow = true
      this.userId = id
    }
  }
}
</script>

<style lang="scss" scoped>
</style>
